<template>
  <CommonImgTemplate>
    <template #topMenu>
      <div class="menu">
        <div class="input">
          <el-input v-model="codeData" placeholder="输入文本" size="small" type="textarea" resize="none"> </el-input>

          <div class="btns">
            <el-button size="small" :disabled="!codeData" type="primary" @click="generateCode">
              生 成
              <i class="iconfont icon-baocun"></i>
            </el-button>
            <a :href="base64Url" download="qrcode.png">
              <el-button type="success" size="small" :disabled="!base64Url">
                保存图片
                <i class="iconfont icon-baocun"></i>
              </el-button>
            </a>
          </div>
        </div>
      </div>
    </template>

    <template #topImg>
      <canvas ref="canvas"></canvas>
    </template>

    <template #bottomMenu>
      <div class="url-title flex-column-center">
        <p>Base64:</p>
        <el-button type="success" size="small" :disabled="!base64Url" @click="useCopy(base64Url)">
          复制地址
          <i class="iconfont icon-fuzhi"></i>
        </el-button>
      </div>
    </template>

    <template #bottomContent>
      <el-input v-model="base64Url" type="textarea" disabled resize="none" />
    </template>
  </CommonImgTemplate>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { showLoading, hiddenLoading, message } from "@/utils/Element";
import QRCode from "qrcode";
import useCopy from "@/hook/useCopy";

const canvas = ref(null);
const codeData = ref("");
const base64Url = ref("");

const generateCode = () => {
  showLoading();
  QRCode.toCanvas(canvas.value, codeData.value, (err: Error | null | undefined) => {
    hiddenLoading();
    if (err) {
      message.error("生成失败: " + err.message);
      return;
    }
  });
  QRCode.toDataURL(codeData.value, (err: Error | null | undefined, url: string) => {
    hiddenLoading();
    if (err) {
      message.error("生成失败: " + err.message);
      return;
    }
    base64Url.value = url;
  });
};
</script>

<style lang="scss" scoped>
@import "@/styles/var.scss";

:deep(.top > .top-menu) {
  align-items: flex-start;
}

.menu {
  width: 100%;
  height: 100%;
  .input {
    height: 100%;
    display: flex;
    // align-items: center;
    :deep(.el-textarea > .el-textarea__inner) {
      height: 100%;
    }
    .btns {
      text-align: center;
      :deep(.el-button) {
        margin-left: 10px;
        margin-bottom: 10px;
      }

      a {
        text-decoration: none;
      }
    }
  }
}

.url-title {
  p {
    color: $success;
    font-weight: bold;
    margin-bottom: 10px;
  }
}

:deep(.bottom-content) {
  .el-textarea {
    height: 100%;
    .el-textarea__inner {
      height: 100%;
    }
  }
}
</style>
